package com.isunland.managesystem.ui;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ListView;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.isunland.managesystem.R;
import com.isunland.managesystem.adapter.MyCircleListAdapter;
import com.isunland.managesystem.base.Base;
import com.isunland.managesystem.base.BaseListFragment;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.CurrentUser;
import com.isunland.managesystem.entity.MyCircle;
import com.isunland.managesystem.entity.MyCircleOriginal;
import com.isunland.managesystem.entity.SuccessMessage;
import com.isunland.managesystem.utils.LogUtil;
import com.isunland.managesystem.utils.MyUtils;
import com.isunland.managesystem.utils.SharedPreferencesUtil;
import com.isunland.managesystem.utils.ToastUtil;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONException;

/**
 * 对象功能:  我的圈子
 * 开发公司: 北京信普达系统工程有限公司
 * 开发人员: HuXiaoDan
 * 创建时间: 2017/3/16 19:05
 */
public class AgriculturalMyCircleListFragment extends BaseListFragment {

  private final int REQUEST_DETAIL = 1;
  private ArrayList<MyCircle> mList;
  private AlertDialog dialog;

  @Override public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setBack(true);
    setTitleCustom(R.string.myCircle);
    mList = new ArrayList<>();
  }

  @Override public String getUrl() {
    return ApiConst.URL_MY_CIRCLE_LIST;
  }

  @Override public HashMap<String, String> getparameters() {
    HashMap<String, String> params = new HashMap<>();
    params.put("jobno", CurrentUser.newInstance(getActivity()).getJobNumber());
    params.put("subCode",
        SharedPreferencesUtil.getString(getActivity(), SharedPreferencesUtil.KEY_FORUM_SUBCODE,
            ""));
    return params;
  }

  @Override public void resolveResponse(String json) {
    MyCircleOriginal original = new Gson().fromJson(json, MyCircleOriginal.class);
    if (original.getResult() == Base.SUCCESS && original.getRows() != null) {
      //获取列表成功
      mList.clear();
      mList.addAll(original.getRows());
      MyCircleListAdapter mAdapter = new MyCircleListAdapter(getActivity(), mList);
      setListAdapter(mAdapter);
    } else {
      ToastUtil.show("获取列表失败");
    }
  }

  @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    //创建圈子
    inflater.inflate(R.menu.menu_add, menu);
    super.onCreateOptionsMenu(menu, inflater);
  }

  @Override public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      case android.R.id.home:
        if (NavUtils.getParentActivityName(getActivity()) != null) {
          NavUtils.navigateUpFromSameTask(getActivity());
        }
        return true;
      case R.id.menu_item_add:
        //创建圈子
        //                Intent add = new Intent(getActivity(), MyCircleAddActivity.class);
        //                startActivityForResult(add, REQUEST_ADD);

        showDialog();
        return true;
      default:
        return super.onOptionsItemSelected(item);
    }
  }

  private void showDialog() {
    final View view = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_edit_text, null);
    final EditText etname = (EditText) view.findViewById(R.id.et_name);
    dialog = new AlertDialog.Builder(getActivity()).setTitle(R.string.addCircleHint)
        .setView(view)
        .setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {
          @Override public void onClick(DialogInterface dialogInterface, int i) {

            volleyPostAdd(etname.getText().toString());
          }
        })
        .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
          @Override public void onClick(DialogInterface dialogInterface, int i) {
            dialog.dismiss();
          }
        })
        .create();
    dialog.show();
  }

  private void volleyPostAdd(String name) {
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_MY_CIRCLE_ADD);
    HashMap<String, String> params = new HashMap<>();
    params.put("cirName", name);
    MyUtils.showDialogLoading(getActivity());
    mActivity.volleyPost(url, params, new VolleyResponse() {
      @Override public void onVolleyError(VolleyError arg0) {

      }

      @Override public void onVolleyResponse(String arg0) throws JSONException {

        MyUtils.dismissDialog();
        dialog.dismiss();
        try {
          SuccessMessage successsMessage = new Gson().fromJson(arg0, SuccessMessage.class);

          String successType = successsMessage.getResult();

          if (successType.equals("1")) {
            ToastUtil.show(R.string.success_operation);
            volleyPost();
          } else {
            ToastUtil.show(R.string.failure_operation);
          }
        } catch (Exception e) {
          LogUtil.e("error", e);
          ToastUtil.show(R.string.failure_operation);
        }
      }
    });
  }

  @Override public void onListItemClick(ListView l, View v, int position, long id) {
    //圈子成员
    MyCircle content = mList.get(position - 1);
    Intent intent = new Intent(getActivity(), MyCircleMembersPagerActivity.class);
    intent.putExtra(MyCircleMembersListFragment.EXTRA_VALUE, content);
    startActivityForResult(intent, REQUEST_DETAIL);
    super.onListItemClick(l, v, position, id);
  }

  @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode != Activity.RESULT_OK) {
      return;
    }
    int REQUEST_ADD = 0;
    if (requestCode == REQUEST_ADD) {
      volleyPost();
    }
    if (requestCode == REQUEST_DETAIL) {
      volleyPost();
    }
    super.onActivityResult(requestCode, resultCode, data);
  }
}
